<?php

// **************************************************************
// | Name: 星空框架 商品管理
// **************************************************************
// | Version： V5.0
// **************************************************************
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// **************************************************************
// | City: 青岛
// **************************************************************
// | Time: 2021-08-19 15:59
// **************************************************************
declare(strict_types=1);

namespace app\xingkong\controller\v1;

use app\common\common\BackendController;
use app\common\model\GoodsCate as GoodsCateModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\Spec as SpecModel;
use app\common\model\GoodsAttr as GoodsAttrModel;
use app\common\model\GoodsPic as GoodsPicModel;
use app\common\model\SpecValue as SpecValueModel;
use app\common\model\SpecPrice as SpecPriceModel;
use app\common\model\GoodsSpec as GoodsSpecModel;
use app\common\model\GoodsSpecValue as GoodsSpecValueModel;
use app\common\model\GoodsOrder as GoodsOrderModel;
use app\common\model\Store as StoreModel;
use app\common\model\Area as AreaModel;
use app\common\services\GoodsServices;
use think\facade\Session;
use think\facade\Db;
use think\facade\View;

/**
 * @xk 商品管理
 */
class Goods extends BackendController
{
    // ***************
    // | 商品分类管理
    // *******************
    /**
     * @xk 商品分类列表
     *
     * @method goodsCate
     * @param  GoodsCateModel $goodsCateModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function goodsCate(GoodsCateModel $goodsCateModel)
    {
        $param = request()->param();
        $parent_id = isset($param['parent_id']) ? $param['parent_id'] : 0;
        $level = isset($param['level']) ? $param['level'] : 1;
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $search_time = isset($param['search_time']) ? $param['search_time'] : '';

            $condition = [];
            if ($keywords != '') {
                $condition[] = ['gc.goods_cate_name','like','%'.$keywords.'%'];
            }
            if ($search_time != '') {
                $search_time_arr = explode('~', $search_time);
                $start_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[0]).' 00:00:00')); //当前时间0点开始
                $end_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[1]).' 23:59:59')); //当前时间0点开始
                $condition[] = ['gc.update_time', 'between time', $start_time.','.$end_time];
            }

            $condition[] = ['gc.level','=',$level];
            $condition[] = ['gc.parent_id','=',$parent_id];
            $resultData = [];
            $resultData['list'] = $goodsCateModel
                            ->alias('gc')
                            ->leftJoin('goodsCate gcc', 'gcc.parent_id=gc.goods_cate_id')
                            ->where($condition)
                            ->field('gc.`goods_cate_id`,gc.`picurl`,gc.`goods_cate_name`,gc.`level`,gc.`status`,gc.`update_time`,gc.`order_id`,count(distinct gcc.`goods_cate_id`) as child_count,gc.`is_top`,gc.`is_hot`')
                            ->withAttr('picurl', function ($value, $data) {
                                return getShowUrl($value);
                            })
                            ->page($page, $limit)
                            ->order('order_id desc')
                            ->group('goods_cate_id')
                            ->select()
                            ->toArray();
            $resultData['count'] = $goodsCateModel
                             ->alias('gc')
                             ->where($condition)
                             ->count();
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        return View::fetch('', ['parent_id'=>$parent_id,'level'=>$level]);
    }
    /**
     * @xk 商品分类添加
     *
     * @method goodsCateCreate
     * @param  GoodsCateModel  $goodsCateModel            [description]
     * @return [type]          [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function goodsCateCreate()
    {
        return View::fetch('');
    }
    /**
     * @xk 商品分类编辑
     *
     * @method goodsCateEdit
     * @param  GoodsCateModel $goodsCateModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function goodsCateEdit(GoodsCateModel $goodsCateModel)
    {
        $param = request()->param();
        $goods_cate_id = isset($param['goods_cate_id']) ? $param['goods_cate_id'] : 0;
        if ($goods_cate_id <= 0) {
            $this->error("请选择需要编辑的产品分类");
        }
        $info = $goodsCateModel
                ->field('*,`picurl` as `show_picurl`,`top_picurl` as `show_top_picurl`')
                ->withAttr('show_picurl', function ($value, $data) {
                    if ($value) {
                        return getShowUrl($value);
                    }
                })
                ->withAttr('show_top_picurl', function ($value, $data) {
                    if ($value) {
                        return getShowUrl($value);
                    }
                })
                ->find($goods_cate_id);
        return View::fetch('', ['info'=>$info]);
    }
    /**
     * @xk 商品分类保存
     *
     * @method goodsCateSave
     * @param  GoodsCateModel $goodsCateModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function goodsCateSave(GoodsCateModel $goodsCateModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $goodsCateModel->validate($param, $act);
            switch ($act) {
              case 'create':
                $res = $goodsCateModel->create($param);
                break;
              case 'edit':
                $res = $goodsCateModel->find($param['goods_cate_id'])->save($param);
                break;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 商品分类动态修改
     *
     * @method goodsCateChanageValue
     * @param  GoodsCateModel        $goodsCateModel            [description]
     * @return [type]                [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function goodsCateChanageValue(GoodsCateModel $goodsCateModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
                throw new \think\Exception("请选择需要修改的产品分类数据", 404);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $goodsCateModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 商品分类删除
     *
     * @method goodsCateDestory
     * @param  GoodsCateModel   $goodsCateModel            [description]
     * @return [type]           [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public function goodsCateDestroy(GoodsCateModel $goodsCateModel, GoodsModel $goodsModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                throw new \think\Exception("请选择需要删除的数据", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $goods_cate_count = $goodsCateModel->where([['parent_id','=',$value]])->count();
                $count = $goodsModel->where([['goods_cate_id', '=', $value]])->whereOr([['goods_cate_str','like','%,'.$value.',%']])->count();
                if ($goods_cate_count > 0) {
                    throw new \think\Exception("存在下级分类无法删除", 404);
                    break;
                }
                if ($count > 0) {
                    throw new \think\Exception("分类下存在产品,请先删除对应的产品", 404);
                    break;
                }
                $res = $goodsCateModel->destroy($value);
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
            if ($j > 0) {
                $result_msg .= '有'.$j.'个分类存在产品不允许删除';
            }
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    // *******************
    // | 商品属性管理
    // **********************
    /**
     * @xk 商品属性列表
     *
     * @method attr
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @return [type]         [description]
     * @Time   2021-10-12
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function attr(GoodsAttrModel $goodsAttrModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $search_time = isset($param['search_time']) ? $param['search_time'] : '';
            $condition = [];
            if ($keywords != '') {
                $condition[] = ['ga.goods_attr_name','like','%'.$keywords.'%'];
            }
            if ($search_time != '') {
                $search_time_arr = explode('~', $search_time);
                $start_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[0]).' 00:00:00')); //当前时间0点开始
                $end_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[1]).' 23:59:59')); //当前时间0点开始
                $condition[] = ['ga.update_time', 'between time', $start_time.','.$end_time];
            }
            $resultData = [];
            $resultData['list'] = $goodsAttrModel
                              ->alias('ga')
                              ->where($condition)
                              ->field('ga.`goods_attr_id`,ga.`goods_attr_name`,ga.`store_id`,ga.`order_id`,ga.`update_time`')
                              ->page($page, $limit)
                              ->order('order_id desc')
                              ->select()
                              ->toArray();
            $resultData['count'] = $goodsAttrModel
                               ->alias('ga')
                               ->where($condition)
                               ->count();
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        return View::fetch('');
    }
    /**
     * @xk 商品属性添加
     *
     * @method attrCreate
     * @return [type]     [description]
     * @Time   2021-10-12
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public function attrCreate()
    {
        return View::fetch('');
    }
    /**
     * @xk 商品属性编辑
     *
     * @method attrEdit
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @return [type]         [description]
     * @Time   2021-10-12
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function attrEdit(GoodsAttrModel $goodsAttrModel)
    {
        $param = request()->param();
        $goods_attr_id = isset($param['goods_attr_id']) ? $param['goods_attr_id'] : 0;
        if ($goods_attr_id <= 0) {
            $this->error("请选择需要编辑的商品属性");
        }
        $info = $goodsAttrModel->find($goods_attr_id);
        return View::fetch('', ['info'=>$info]);
    }
    /**
     * @xk 商品属性保存
     *
     * @method attrSave
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function attrSave(GoodsAttrModel $goodsAttrModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData= [];
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $goodsAttrModel->validate($param, $act);
            switch ($act) {
              case 'create':
                $res = $goodsAttrModel->create($param);
                break;
              case 'edit':
                $res = $goodsAttrModel->find($param['goods_attr_id'])->save($param);
                break;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '更新成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 商品属性动态修改
     *
     * @method attrChanageValue
     * @param  GoodsAttrModel   $goodsAttrModel            [description]
     * @return [type]           [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public function attrChanageValue(GoodsAttrModel $goodsAttrModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
                throw new \think\Exception("请选择需要修改的数据", 404);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $goodsAttrModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 商品属性删除
     *
     * @method attrDestroy
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function attrDestroy(GoodsAttrModel $goodsAttrModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                throw new \think\Exception("请选择需要删除的数据", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $goodsAttrModel->destroy($value); // 删除后操作 对应的规格信息同步删除
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
            if ($j > 0) {
                $result_msg .= '有'.$j.'个产品属性存在产品不允许删除';
            }
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }

    // *************
    // | 商品规格系统模型
    // ********************
    /**
     * @xk 商品规格系统模型
     *
     * @method spec
     * @param  SpecModel      $specModel                 [description]
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-20
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function spec(SpecModel $specModel, GoodsAttrModel $goodsAttrModel)
    {
        $param = request()->param();
        $goods_attr_id = isset($param['goods_attr_id']) ? $param['goods_attr_id'] : 0;
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $search_time = isset($param['search_time']) ? $param['search_time'] : '';
            $condition = [];
            if ($keywords != '') {
                $condition[] = ['s.spec_name|s.spec_value_str','like','%'.$keywords.'%'];
            }
            if ($search_time != '') {
                $search_time_arr = explode('~', $search_time);
                $start_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[0]).' 00:00:00')); //当前时间0点开始
                $end_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[1]).' 23:59:59')); //当前时间0点开始
                $condition[] = ['s.update_time', 'between time', $start_time.','.$end_time];
            }
            if ($goods_attr_id > 0) {
                $condition[] = ['s.goods_attr_id','=',$goods_attr_id];
            }
            $resultData = [];
            $resultData['list'] = $specModel
                              ->alias('s')
                              ->leftJoin('goodsAttr ga', 'ga.goods_attr_id=s.goods_attr_id')
                              ->where($condition)
                              ->field('s.`spec_id`,s.`spec_value_str`,s.`spec_name`,ga.`goods_attr_name`,s.`order_id`,s.`update_time`')
                              ->select()
                              ->toArray();
            $resultData['count'] = $specModel
                               ->alias('s')
                               ->where($condition)
                               ->count();
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        $goods_attr_list = $goodsAttrModel
                         ->alias('ga')
                         ->field('ga.`goods_attr_id`,ga.`goods_attr_name`')
                         ->order('order_id desc')
                         ->select()
                         ->toArray();
        return View::fetch('', ['goods_attr_list'=>$goods_attr_list,'goods_attr_id'=>$goods_attr_id]);
    }
    /**
     * @xk 商品规格系统模型添加
     *
     * @method specCreate
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function specCreate(GoodsAttrModel $goodsAttrModel)
    {
        $param = request()->param();
        $goods_attr_id = isset($param['goods_attr_id']) ? $param['goods_attr_id'] : 0;
        $goods_attr_list = $goodsAttrModel
                         ->alias('ga')
                         ->where([['ga.status', '=', 1]])
                         ->field('ga.`goods_attr_id`,ga.`goods_attr_name`')
                         ->order('order_id desc')
                         ->select()
                         ->toArray();
        return View::fetch('', ['goods_attr_list'=>$goods_attr_list,'goods_attr_id'=>$goods_attr_id]);
    }
    /**
     * @xk 商品规格系统模型编辑
     *
     * @method specEdit
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @param  SpecModel      $specModel                 [description]
     * @param  SpecValueModel $specValueModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function specEdit(GoodsAttrModel $goodsAttrModel, SpecModel $specModel, SpecValueModel $specValueModel)
    {
        $param = request()->param();
        $spec_id = isset($param['spec_id']) ? $param['spec_id'] : 0;
        if ($spec_id <= 0) {
            $this->error('请选择需要编辑的产品规格');
        }
        $info = $specModel->find($spec_id);
        $goods_attr_list = $goodsAttrModel
                        ->alias('ga')
                        ->where([['ga.status', '=', 1]])
                        ->field('ga.`goods_attr_id`,ga.`goods_attr_name`')
                        ->order('order_id desc')
                        ->select()
                        ->toArray();
        $spec_value_list = $specValueModel
                     ->where([['spec_id', '=', $spec_id]])
                     ->column('spec_value');

        return View::fetch('', ['info' => $info, 'spec_value_list' => implode("\n", $spec_value_list), 'goods_attr_list' => $goods_attr_list]);
    }
    /**
     * @xk 商品规格系统模型保存
     *
     * @method sepcSave
     * @param  SpecModel      $specModel                 [description]
     * @param  SpecValueModel $specValueModel            [description]
     * @return [type]         [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function specSave(SpecModel $specModel, SpecValueModel $specValueModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $check_result = $specModel->validate($param, $act);
            $values = chanageStringToArray(isset($param['values']) ? $param['values'] : '');
            unset($param['values']);
            $param['spec_value_str'] = implode(',', $values);
            switch ($act) {
            case 'create':
              $res = $specModel->create($param); // 写入更新
              // 写入规格属性值
              $spec_id = $res->spec_id;
              break;
            case 'edit':
              $res = $specModel->find($param['spec_id'])->save($param);
              // 新增不存在的规格属性值
              $spec_id = $param['spec_id'];
              break;
          }

            // 查询已经存在的规格值
            $spec_value_list = $specValueModel->where([['spec_id', '=', $spec_id]])->column('spec_value', 'spec_value_id');

            $create_values_data = [];
            foreach ($values as $key => $value) {
                if (!in_array($value, $spec_value_list)) {
                    $create_values_data[] = ['spec_id' => $spec_id, 'spec_value' => $value];
                }
            }
            if ($create_values_data) {
                $spec_value_create_res = $specValueModel->saveAll($create_values_data);
            }

            // 不存在的删除
            $destroy_values_data = [];
            foreach ($spec_value_list as $key => $value) {
                if (!in_array($value, $values)) {
                    $destroy_values_data[] = $key;
                }
            }
            if ($destroy_values_data) {
                $spec_destroy_res = $specValueModel->destroy($destroy_values_data);
            }

            Db::commit();
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 商品规格系统模型删除
     *
     * @method specDestroy
     * @param  SpecModel   $specModel                 [description]
     * @return [type]      [description]
     * @Time   2021-08-19
     * @City   青岛
     * @Author xkyinzhe    <zhonghuaxinxing@sina.cn>
     */
    public function specDestroy(SpecModel $specModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                throw new \think\Exception("请选择需要删除的数据", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $specModel->destroy($value); // 删除后操作 对应的规格值  规格价格列表同步删除
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // *******************
    // | 商品管理
    // **********************
    /**
     * @xk 商品列表
     *
     * @method goodsList
     * @param  GoodsModel     $goodsModel                [description]
     * @param  GoodsCateModel $goodsCateModel            [description]
     * @param  StoreModel     $storeModel                [description]
     * @return [type]         [description]
     * @Time   2021-08-20
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function goodsList(GoodsModel $goodsModel, GoodsCateModel $goodsCateModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int)$param['page'] : 1;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30;
            $search_time = isset($param['search_time']) ? $param['search_time'] : '';
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $is_onsell = isset($param['is_onsell']) ? $param['is_onsell'] : '';
            $is_new = isset($param['is_new']) ? $param['is_new'] : '';
            $is_tj = isset($param['is_tj']) ? $param['is_tj'] : '';
            $goods_cate_id = isset($param['goods_cate_id']) ? $param['goods_cate_id'] : '';
            $condition = [];
            if ($search_time != '') {
                $search_time_arr = explode('~', $search_time);
                $start_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[0]).' 00:00:00')); //当前时间0点开始
              $end_time = date('Y-m-d H:i:s', strtotime(trim($search_time_arr[1]).' 23:59:59')); //当前时间0点开始
              $condition[] = ['g.update_time', 'between time', $start_time.','.$end_time];
            }
            if ($keywords != '') {
                $condition[] = ['g.goods_name|g.content|g.mobile_content|g.keyword','like','%'.$keywords.'%'];
            }
            if ($is_onsell != '') {
                $condition[] = ['g.is_onsell','in',$is_onsell];
            }
            if ($is_new != '') {
                $condition[] = ['g.is_new','in',$is_new];
            }
            if ($is_tj != '') {
                $condition[] = ['g.is_tj','in',$is_tj];
            }
            if ($goods_cate_id != '') {
                $condition[] = ['g.goods_cate_str','like','%,'.$goods_cate_id.',%'];
            }
            // 开始组合查询条件
            $resultData = [];
            $resultData['list'] = $goodsModel
                              ->alias('g')
                              ->leftJoin('goodsCate gc', 'g.goods_cate_id=gc.goods_cate_id')
                              ->leftJoin('store s', 's.store_id=g.store_id')
                              ->where($condition)
                              ->field('g.`goods_id`,g.`picurl`,g.`goods_name`,g.`selling_price`,g.`market_price`,g.`achievement_bili`,g.`bonus_type`,g.`bonus_price`,g.`stock`,g.`warn_stock`,g.`shell_num`,g.`order_id`,g.`update_time`,gc.`goods_cate_name`,g.`is_onsell`,g.`is_new`,g.`is_tj`,s.`store_name`,g.`is_buy`,g.`is_supper`')
                              ->withAttr('picurl', function ($value, $data) {
                                  if ($value) {
                                      return getShowUrl($value);
                                  }
                              })
                              ->withAttr('is_tj', function ($value, $data) {
                                  return $value==1 ? '<span style="color:green">推荐</span>' : '<span style="color:red">未推荐</span>';
                              })
                              ->withAttr('is_buy', function ($value, $data) {
                                  return $value==1 ? '<span style="color:green">正常购买</span>' : '<span style="color:red">不可购买</span>';
                              })
                              ->withAttr('is_onsell', function ($value, $data) {
                                  return $value==1 ? '<span style="color:green">正在售卖</span>' : '<span style="color:red">未上架</span>';
                              })
                              ->withAttr('is_supper', function ($value, $data) {
                                  return $value==1 ? '<span style="color:green">单品拆单</span>' : '<span style="color:red">单品不拆单</span>';
                              })
                              ->page($page, $limit)
                              ->order('order_id desc')
                              ->select()
                              ->toArray();
            $resultData['count'] = $goodsModel
                               ->alias('g')
                               ->where($condition)
                               ->count();
            $this->result(200, '请求成功', 200, '加载成功', $resultData);
        }
        $goods_cate_list = $goodsCateModel->getTreeList('goods_cate_id');
        return View::fetch();
    }
    /**
     * @xk 商品创建
     *
     * @method goodsCreate
     * @param  GoodsCateModel $goodsCateModel            [description]
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @param  StoreModel     $storeModel                [description]
     * @return [type]         [description]
     * @Time   2021-08-20
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function goodsCreate(GoodsAttrModel $goodsAttrModel, GoodsCateModel $goodsCateModel, StoreModel $storeModel)
    {
        $goods_cate_list = $goodsCateModel
                            ->where([['status','=',1]])
                            ->field('`goods_cate_id`,`goods_cate_name`')
                            ->select()
                            ->toArray();
        $goods_attr_list = $goodsAttrModel
                         ->alias('ga')
                         ->where([['ga.status','=',1]])
                         ->field('ga.`goods_attr_id`,ga.`goods_attr_name`')
                         ->select()
                         ->toArray();
        $store_list = $storeModel
                      ->where([['status','=',1]])
                      ->field('`store_id`,`store_name`')
                      ->select()
                      ->toArray();
        return View::fetch('', ['goods_attr_list'=>$goods_attr_list,'store_list'=>$store_list,'goods_cate_list'=>$goods_cate_list]);
    }
    /**
     * @xk 商品编辑
     *
     * @method goodsEdit
     * @param  GoodsModel     $goodsModel                [description]
     * @param  GoodsCateModel $goodsCateModel            [description]
     * @param  GoodsAttrModel $goodsAttrModel            [description]
     * @param  StoreModel     $storeModel                [description]
     * @return [type]         [description]
     * @Time   2021-08-24
     * @City   青岛
     * @Author xkyinzhe       <zhonghuaxinxing@sina.cn>
     */
    public function goodsEdit(GoodsModel $goodsModel, GoodsCateModel $goodsCateModel, GoodsAttrModel $goodsAttrModel, StoreModel $storeModel)
    {
        $goods_cate_list = $goodsCateModel
                            ->where([['status','=',1]])
                            ->field('`goods_cate_id`,`goods_cate_name`')
                            ->select()
                            ->toArray();
        $goods_attr_list = $goodsAttrModel
                       ->alias('ga')
                       ->where([['ga.status','=',1]])
                       ->field('ga.`goods_attr_id`,ga.`goods_attr_name`')
                       ->select()
                       ->toArray();
        $store_list = $storeModel
                      ->where([['status','=',1]])
                      ->field('`store_id`,`store_name`')
                      ->select()
                      ->toArray();
        $param = request()->param();
        $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
        if ($goods_id <= 0) {
            $this->error("请选择需要编辑的产品数据");
        }
        $info = $goodsModel
              ->with(['getGoodsParameters'])
              ->field('*,`picurl` as show_picurl,fileurl as show_fileurl')
              ->find($goods_id)
              ->withAttr('show_picurl', function ($value, $data) {
                  if ($value) {
                      return getShowUrl($value);
                  }
              })
              ->withAttr('show_fileurl', function ($value, $data) {
                  if ($value) {
                      return getShowUrl($value);
                  }
              });
        return View::fetch('', ['goods_attr_list'=>$goods_attr_list,'store_list'=>$store_list,'info'=>$info,'goods_cate_list'=>$goods_cate_list]);
    }
    /**
     * @xk 获取产品图片
     *
     * @method getGoodsPic
     * @param  GoodsPicModel $goodsPicModel             [description]
     * @return [type]        [description]
     * @Time   2021-08-24
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public function getGoodsPic(GoodsPicModel $goodsPicModel)
    {
        $param = request()->param();
        $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
        $code = 200;
        $msg = '请求成功';
        if ($goods_id <= 0) {
            $result_code = 404;
            $result_msg = '请选择需要获取的产品';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $condition = [];
        $condition[] = ['goods_id', '=', $goods_id];
        $list = $goodsPicModel
      ->where($condition)
      ->field('`picurl`,`picurl`as show_picurl,`picname` as name,`picsize` as size')
      ->withAttr('show_picurl', function ($value, $data) {
          if ($value) {
              return getShowUrl($value);
          }
      })
      ->select()
      ->toArray();
        $new_list = [];
        if ($list) {
            foreach ($list as $key => $value) {
                $new_list[]['file'] = $value;
            }
        }
        $result_code = 200;
        $result_msg = '请求成功';
        $resultData = [];
        $resultData['list'] = $new_list;
        $resultData['all_size'] = $goodsPicModel->where($condition)->sum('picsize');
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 商品保存
     *
     * @method goodsSave
     * @param  GoodsModel    $goodsModel                [description]
     * @param  GoodsServices $goodsServices             [description]
     * @return [type]        [description]
     * @Time   2021-08-20
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public function goodsSave(GoodsModel $goodsModel, GoodsServices $goodsServices)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $act = isset($param['act']) ? $param['act'] : 'create';
            $spec_list = isset($param['spec_list']) ? $param['spec_list'] : '';
            $sku_data = isset($param['sku']) ? $param['sku'] : '';
            $attr_key_data = isset($param['attr_key']) ? $param['attr_key'] : '';
            $attr_value_data = isset($param['attr_value']) ? $param['attr_value'] : '';
            $param['pic_arr'] = isset($param['pic_arr']) ? $param['pic_arr'] : '';
            $goods_attr_id = isset($param['goods_attr_id']) ? $param['goods_attr_id'] : 0;
            if($sku_data == ''){
              throw new \think\Exception("请最少上传一个产品规格", 404);
            }
            // 整合产品规格信息
            if ($sku_data) {
                $selling_price_min = min(array_column($sku_data, 'selling_price'));
                $market_price_min = 0;
                $achievement_bili_min = min(array_column($sku_data, 'achievement_bili'));
                $bonus_price_min = min(array_column($sku_data,'bonus_price'));
                $next_bonus_price_min = min(array_column($sku_data,'next_bonus_price'));
                $param['selling_price'] = $selling_price_min > 0 ? $selling_price_min : $param['selling_price'];
                $param['achievement_bili'] = $achievement_bili_min>0 ? $achievement_bili_min : $param['achievement_bili'];
                $param['bonus_price'] = $bonus_price_min>0?$bonus_price_min:0;
                $param['next_bonus_price'] = $next_bonus_price_min>0?$next_bonus_price_min:0;
            }
            $param['goods_sn'] = $goodsModel->getGoodsSn($param['goods_sn']);
            // 开始组合三级分类数据
            $param['goods_cate_str'] = '0,'.$param['goods_cate_id'].',';
            $param['goods_cate_id'] = $param['goods_cate_id'];
            $goodsModel->validate($param, $act);
            // 组合三级分类结束
            switch ($act) {
              case 'create':
                $res = $goodsModel->create($param);
                $goods_id = $res->goods_id;
                break;
              case 'edit':
                $res = $goodsModel->find($param['goods_id'])->save($param);
                $goods_id = $param['goods_id'];
            }
            // 生成成功后  产品图片资料更新
            $goods_pic_res = $goodsServices->updateGoodsPic($goods_id, $param['pic_arr'], $param['pic_name'], $param['pic_size']);
            // 生成成功后 产品服务开始 更新产品参数体系
            if ($goods_attr_id > 0) {
                // 生成成功后 产品服务开始 更新产品规格体系模型 以及写入产品规格价格体系
                $goods_spec_price_res = $goodsServices->updateSpec($goods_id, $goods_attr_id, $spec_list, $sku_data);
            }
            $car_res = $goodsServices->updateCar($goods_id);
            Db::commit();
            $result_code = 200;
            $result_msg = '更新成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 产品信息动态调整
     *
     * @method goodsChanageValue
     * @param  GoodsModel        $goodsModel                [description]
     * @return [type]            [description]
     * @Time   2021-08-24
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function goodsChanageValue(GoodsModel $goodsModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $by_key = isset($param['by_key']) ? $param['by_key'] : '';
            $i = 0;
            $j = 0;
            if (!$by_key) {
                throw new \think\Exception("请选择需要调整的数据", 404);
            }
            $by_key_arr = explode(',', $by_key);
            foreach ($by_key_arr as $key => $value) {
                $newarr = [];
                $newarr['by_key'] = $value;
                $newarr['key'] = $param['key'];
                $newarr['value'] = $param['value'];
                $res = $goodsModel->chanageValue($newarr);
                if ($res) {
                    ++$i;
                }
            }
            $result_code = 200;
            $result_msg = '处理成功';
            Db::commit();
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
            Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg);
    }
    /**
     * @xk 产品删除操作
     *
     * @method goodsDestroy
     * @param  GoodsModel   $goodsModel                [description]
     * @return [type]       [description]
     * @Time   2021-08-20
     * @City   青岛
     * @Author xkyinzhe     <zhonghuaxinxing@sina.cn>
     */
    public function goodsDestroy(GoodsModel $goodsModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        try {
            $param = request()->param();
            $id_str = isset($param['id_str']) ? $param['id_str'] : '';
            $i = 0;
            $j = 0;
            if (!$id_str) {
                throw new \think\Exception("请选择需要删除的数据", 404);
            }
            $id_arr = explode(',', $id_str);
            foreach ($id_arr as $key => $value) {
                $res = $goodsModel->destroy($value); // 删除后操作 对应的规格值  规格价格列表同步删除
                ++$i;
            }
            Db::commit();
            $result_code = 200;
            $result_msg = '处理成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg);
    }
    // ***************
    // | 商品规格获取
    // | 根据属性和商品id进行查询
    // ****************************
    /**
     * @xk 商品规格&&规格值动态获取
     *
     * @method getSpecList
     * @param  SpecModel           $specModel                 [description]
     * @param  SpecValueModel      $specValueModel            [description]
     * @param  GoodsSpecModel      $goodsSpecModel            [description]
     * @param  GoodsSpecValueModel $goodsSpecValueModel       [description]
     * @param  SpecPriceModel      $specPriceModel            [description]
     * @return [type]              [description]
     * @Time   2021-08-24
     * @City   青岛
     * @Author xkyinzhe            <zhonghuaxinxing@sina.cn>
     */
    public function getSpecList(SpecModel $specModel, SpecValueModel $specValueModel, GoodsSpecModel $goodsSpecModel, GoodsSpecValueModel $goodsSpecValueModel, SpecPriceModel $specPriceModel)
    {
        $param = request()->param();
        $goods_attr_id = isset($param['goods_attr_id']) ? $param['goods_attr_id'] : 0;
        $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            if ($goods_attr_id <= 0) {
                throw new \think\Exception("请选择产品对应的属性", 404);
            }
            // 开始查询 规格 规格值 系统模型
            $condition = [];
            $condition[] = ['s.goods_attr_id', '=', $goods_attr_id];
            $list = $specModel
                  ->with(['getSpecValue'])
                  ->alias('s')
                  ->where($condition)
                  ->field('s.`spec_name`,s.`spec_id`,s.`spec_id` as jichu')
                  ->withAttr('jichu', function ($value, $data) {
                      return -3920;
                  })
                  ->select()
                  ->toArray();
            $goods_spec_list = [];
            // 开始判断是否存在产品&&产品模型
            if ($goods_id > 0) {
                $condition[] = ['s.goods_id','=',$goods_id];
                // 如果产品存在
                $goods_spec_list = $goodsSpecModel
                      ->with(['getSpecValue'])
                      ->alias('s')
                      ->where($condition)
                      ->field('s.`spec_name`,s.`goods_spec_id`')
                      ->select()
                      ->toArray();
                $spec_price = $specPriceModel->where([['goods_id', '=', $goods_id]])->column('GROUP_CONCAT(`sku_key` SEPARATOR "_") AS items_id');
                // dump($spec_price); die();
                if ($goods_spec_list && $spec_price[0]) {
                    $spec_arr = explode('_', $spec_price[0]);
                    foreach ($goods_spec_list as $key => $value) {
                        if ($value['getSpecValue']) {
                            foreach ($value['getSpecValue'] as $k => $val) {
                                $goods_spec_list[$key]['getSpecValue'][$k]['is_checked'] = 0;
                                if (in_array($val['goods_spec_value_id'], $spec_arr)) {
                                    $goods_spec_list[$key]['getSpecValue'][$k]['is_checked'] = 1;
                                }
                            }
                        }
                    }
                }
            }
            $resultData['list'] = $goods_spec_list ? $goods_spec_list : $list;
            $resultData['type'] = $goods_spec_list ? 1 : 0;
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取规格参数组合
     * @method ajaxGetSpecInput
     * @return [type]           [description]
     * @Time   2021-08-22
     * @City   青島
     * @Author xkyinzhe         <zhonghuaxinxing@sina.cn>
     */
    public function getSpecInput(SpecPriceModel $specPriceModel)
    {
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        try {
            $param = request()->param();
            $spec_arr = isset($param['spec_arr']) ? $param['spec_arr'] : '';
            $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
            if ($spec_arr == '') {
                throw new \think\Exception("没有选中的规格", 404);
            }
            ksort($spec_arr);
            $clo_name = array_column($spec_arr, 'name');
            $spec_arr1 = array_column($spec_arr, 'spec_name');
            $spec_arr2 = combineDika($spec_arr1); //  获取 规格的 笛卡尔积
            $html = '<table class="layui-table" lay-size="lg" id="spec_input_tab"><tr>';
            foreach ($clo_name as $key => $value) {
                $html .= '<td style="width:80px !important;">'.$value.'</td>';
            }
            $html .= '<td>销售价</td><td>业绩系数</td><td>首购佣金金额</td><td>复购佣金金额</td><td>规格图片</td><td>商品条码</td></tr>';
            foreach ($spec_arr2 as $k => $v) {
                $html .= '<tr>';
                $item_key_name = [];
                foreach ($v as $k2 => $v2) {
                    $html .= "<td>".$v2['sku_name']."</td>";
                    $item_key_name[$v2['sku_key']] = $v2['sku_name'];
                }
                ksort($item_key_name);
                $key = $k + 1;
                $item_key = implode('_', array_keys($item_key_name));
                $key_arr = array_keys($item_key_name);
                $new_key_arr = [];
                foreach ($key_arr as $km => $vm) {
                    $value_arr = explode(":", $vm);
                    $new_key_arr[] = $value_arr[1];
                }
                $item_key_str = implode('_', $new_key_arr);
                $spec_price = [];
                $spec_price = $specPriceModel
                  ->where([['goods_id', '=', $goods_id], ['sku_key', '=', $item_key_str]])
                  ->field('`goods_id`,`sku_key`,`sku_value`,`selling_price`,`market_price`,`picurl`,`sku`,`achievement_bili`,`bonus_price`,`next_bonus_price`,`stock`,`picurl` as show_picurl')
                  ->withAttr('show_picurl', function ($value, $data) {
                      if ($value && $value != '/static/common/images/no_pic.png') {
                          return getShowUrl($value);
                      }
                  })
                  ->find();
                $item_name = implode(' ', $item_key_name);
                $selling_price = isset($spec_price['selling_price']) ? $spec_price['selling_price'] : '';
                $achievement_bili = isset($spec_price['achievement_bili']) ? $spec_price['achievement_bili'] : '';
                $bonus_price = isset($spec_price['bonus_price']) ? $spec_price['bonus_price'] : '';
                $next_bonus_price = isset($spec_price['next_bonus_price']) ? $spec_price['next_bonus_price'] : '';
                $real_num = isset($spec_price['real_num']) ? $spec_price['real_num'] : '';
                $stock = isset($spec_price['stock']) ? $spec_price['stock'] : '';
                $sku = isset($spec_price['sku']) ? $spec_price['sku'] : '';
                $picurl = isset($spec_price['picurl']) ? $spec_price['picurl'] : '';
                $show_picurl = isset($spec_price['show_picurl']) ? $spec_price['show_picurl'] : '';
                $html .= "<td><input type='text' class='layui-input' name='sku[$item_key][selling_price]' value='$selling_price' placeholder='0.00' ></td>";
                $html .= "<td><input type='text' class='layui-input' name='sku[$item_key][achievement_bili]' value='$achievement_bili' placeholder='0.00' ></td>";
                $html .= "<td><input type='text' class='layui-input' name='sku[$item_key][bonus_price]' value='$bonus_price' placeholder='0.00' ></td>";
                $html .= "<td><input type='text' class='layui-input' name='sku[$item_key][next_bonus_price]' value='$next_bonus_price' placeholder='0.00' ></td>";
                if ('' != $picurl && $picurl != '/static/common/images/no_pic.png') {
                    $html .= '<td><div class="layui-upload xz666" style="display:flex;align-items: center;"><div class="xk-big-show" datasrc="'.$show_picurl.'"><input type="hidden" class="xk-picurl" name="sku['.$item_key.'][picurl]" value="'.$picurl.'"><img class="layui-upload-img  xk-img xk-upload-pic" src="'.$show_picurl.'" width="100px" height="100px"></div><button class="layui-btn layui-btn-danger layui-btn-sm xk-del-pic" type="button" name="button"><i class="layui-icon"></i></button></div></td>';
                } else {
                    $picurl = '/static/common/images/no_pic.png';
                    $html .= '<td><div class="layui-upload xz666" style="display:flex;align-items: center;"><div class="xk-big-show" datasrc="'.$picurl.'"><input type="hidden" class="xk-picurl" name="sku['.$item_key.'][picurl]" value="'.$picurl.'"><img class="layui-upload-img  xk-img xk-upload-pic" src="'.$picurl.'" width="100px" height="100px"></div></div></td>';
                }
                $html .= "<td><input type='text' class='layui-input' name='sku[$item_key][sku]' value='$sku' placeholder='' ><input type='hidden' class='layui-input' name='sku[$item_key][sku_value]' value='$item_name' /><input type='hidden' class='layui-input' name='sku[$item_key][sku_key]' value='$item_key' /></td>";
                $html .='</tr>';
            }
            $html .= '</table>';
            $resultData = [];
            $resultData['html'] = $html;
        } catch (\Exception $e) {
            $resultData = [];
            $resultData['html'] = '';
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    // ************
    // | 商品统计
    // *********************
    /**
     * @xk 商品统计
     * @method                                      statistics
     * @param                                       SpecPriceModel $specPriceModel  [description]
     * @param                                       GoodsOrderModel $goodsOrderModel  [description]
     * @param                                       StoreModel $storeModel  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-25Tfalse15:false28:false19+080
     */
    public function statistics(SpecPriceModel $specPriceModel, GoodsOrderModel $goodsOrderModel, StoreModel $storeModel)
    {
        $param = request()->param();
        if (request()->isAjax()) {
            $page = isset($param['page']) ? (int)$param['page'] : 0;
            $limit = isset($param['limit']) ? (int)$param['limit'] : 30;
            $keywords = isset($param['keywords']) ? $param['keywords'] : '';
            $store_id = isset($param['store_id']) ? $param['store_id'] : '';
            $province = isset($param['province'])?$param['province']:'';
            $city = isset($param['city'])?$param['city']:'';
            $search_time = isset($param['search_time']) ? $param['search_time'] : ''; // 用户下单时间
            $condition = [];
            if ($keywords != '') {
                $condition[] = ['goods_name|spec_value','like','%'.$keywords.'%'];
            }
            if ($store_id != '') {
                $condition[] = ['store_id','in',$store_id];
            }
            if($province != ''){
              $condition[] = ['province','like','%'.$province.'%'];
            }
            if($city != ''){
              $condition[] = ['city','like','%'.$city.'%'];
            }
            $result_count = $goodsOrderModel
                    ->where($condition)
                    ->group('goods_id,spec_key')
                    ->count();
            $online_pay = 0.00;
            $shop_pay = 0.00;
            $all_pay = 0.00;
            $list = $goodsOrderModel
                    ->where($condition)
                    ->field('`goods_pic`,`goods_name`,`goods_id`,`spec_key`,`spec_value`')
                    ->withAttr('goods_pic',function($value,$data){
                      return getShowUrl($value);
                    })
                    ->group('goods_id,spec_key')
                    ->select()
                    ->toArray();
            if($list){
              foreach ($list as $key => $value) {
                $public_condition = [];
                $public_condition[] = ['goods_id','=',$value['goods_id']];
                $public_condition[] = ['spec_key','=',$value['spec_key']];
                if ('' != $search_time) {
                    $search_time_arr = explode('~', $search_time);
                    $start_time = $search_time_arr[0];
                    $end_time = $search_time_arr[1];
                    $public_condition[] = ['receiving_time', 'between time', $start_time.','.$end_time];
                }
                $over_condition= $public_condition;
                $over_condition[] = ['status','in','3.1,4.1'];
                $list[$key]['all_count'] = $goodsOrderModel
                                          ->where($over_condition)
                                          ->sum('buy_num');
                $list[$key]['all_price'] = $goodsOrderModel
                                         ->where($over_condition)
                                         ->sum('sub_total');
                $list[$key]['first_count'] = $goodsOrderModel
                                          ->where($over_condition)
                                          ->where([['is_buy','=',0]])
                                          ->sum('buy_num');
                $list[$key]['first_price'] = $goodsOrderModel
                                           ->where($over_condition)
                                           ->where([['is_buy','=',0]])
                                           ->sum('sub_total');
                $list[$key]['next_count'] = $goodsOrderModel
                                           ->where($over_condition)
                                           ->where([['is_buy','=',1]])
                                           ->sum('buy_num');
                $list[$key]['next_price'] = $goodsOrderModel
                                          ->where($over_condition)
                                          ->where([['is_buy','=',1]])
                                          ->sum('sub_total');
                $online_pay += $goodsOrderModel->where($over_condition)->where([['pay_type','in','1,2,4']])->sum('sub_total');
                $shop_pay += $goodsOrderModel->where($over_condition)->where([['pay_type','=',3]])->sum('sub_total');
                $all_pay += $goodsOrderModel->where($over_condition)->sum('sub_total');
                // if($list[$key]['first_count']+$list[$key]['next_count'] <= 0){
                //   unset($list[$key]);
                // }
              }
            }

            $resultData = [];
            $resultData['list'] = $list;
            $resultData['count'] = $result_count;
            $resultData['show_count'] = '订单合计：'.$all_pay.'元;  线上支付：'.$online_pay.'元，余额支付：'.$shop_pay.'元';
            $this->result(200, '请求成功', 200, '查询成功', $resultData);
        }
        $store_list = $storeModel->field('`store_id`,`store_name`')->select()->toArray();
        return View::fetch('', ['store_list'=>$store_list]);
    }
    /**
     * @xk 商品规格统计导出
     *
     * @method exportStatisticsShow
     * @param  SpecPriceModel       $specPriceModel            [description]
     * @param  GoodsOrderModel      $goodsOrderModel           [description]
     * @return [type]               [description]
     * @Time   2021-11-08
     * @City   青岛
     * @Author xkyinzhe             <zhonghuaxinxing@sina.cn>
     */
    public function exportStatistics(SpecPriceModel $specPriceModel, GoodsOrderModel $goodsOrderModel)
    {
        $param = request()->param();
        $keywords = isset($param['keywords']) ? $param['keywords'] : '';
        $store_id = isset($param['store_id']) ? $param['store_id'] : '';
        $search_time = isset($param['search_time']) ? $param['search_time'] : ''; // 用户下单时间
        $province = isset($param['province'])?$param['province']:'';
        $city = isset($param['city'])?$param['city']:'';
        $condition = [];
        if ($keywords != '') {
            $condition[] = ['goods_name|spec_value','like','%'.$keywords.'%'];
        }
        if ($store_id > 0) {
            $condition[] = ['store_id','=',$store_id];
        }
        if($province != ''){
          $condition[] = ['province','like','%'.$province.'%'];
        }
        if($city != ''){
          $condition[] = ['city','like','%'.$city.'%'];
        }
        $allCount = $goodsOrderModel
                ->where($condition)
                ->group('goods_id,spec_key')
                ->count();
        $limit = 10000;
        $pages = ceil($allCount / $limit);
        for ($i = 1; $i <= $pages; ++$i) {
            $data = $goodsOrderModel
                    ->where($condition)
                    ->field('`goods_pic`,`goods_name`,`goods_id`,`spec_key`,`spec_value`')
                    ->withAttr('goods_pic',function($value,$data){
                      return getShowUrl($value);
                    })
                    ->group('goods_id,spec_key')
                    ->select()
                    ->toArray();
            $order_data = [];
            if ($data) {
                foreach ($data as $key => $value) {
                    $arrays = [];
                    $arrays[] = $value['goods_name'];
                    $arrays[] = $value['spec_value'];
                    $public_condition = [];
                    $public_condition[] = ['goods_id','=',$value['goods_id']];
                    $public_condition[] = ['spec_key','=',$value['spec_key']];
                    if ('' != $search_time) {
                        $search_time_arr = explode('~', $search_time);
                        $start_time = $search_time_arr[0];
                        $end_time = $search_time_arr[1];
                        $public_condition[] = ['receiving_time', 'between time', $start_time.','.$end_time];
                    }
                    $over_condition= $public_condition;
                    $over_condition[] = ['status','in','3.1,4.1'];
                    $arrays[] = $goodsOrderModel
                                ->where($over_condition)
                                ->sum('buy_num');
                    $arrays[] = $goodsOrderModel
                                     ->where($over_condition)
                                     ->sum('sub_total');
                    $arrays[] = $goodsOrderModel
                                ->where($over_condition)
                                ->where([['is_buy','=',0]])
                                ->sum('buy_num');
                    $arrays[] = $goodsOrderModel
                                ->where($over_condition)
                                ->where([['is_buy','=',0]])
                                ->sum('sub_total');
                    $arrays[] = $goodsOrderModel
                                ->where($over_condition)
                                ->where([['is_buy','=',1]])
                                ->sum('buy_num');
                    $arrays[] = $goodsOrderModel
                              ->where($over_condition)
                              ->where([['is_buy','=',1]])
                              ->sum('sub_total');
                    $order_data[] = $arrays;
                }
                $title = ['产品名称','产品规格','确认收货数量','确认收货总金额','首购数量','首购金额','复购数量','复购金额'];
                $width = [40,40,20,20,20,20,20,20];
                $path = '/export/goodsSpec';
                $result = $specPriceModel->export($title, $order_data, $path, $width, $i);
                $url_arr[] = $result;
            }
        }
        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '导出成功';
        $resultData = $url_arr;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取省市区
     * @param  AreaModel $areaModel               [description]
     * @return [type]               [description]
     */
    public function getArea(AreaModel $areaModel)
    {
        $param = request()->param();
        $p_code = isset($param['p_code']) ? $param['p_code'] : '100000';
        $condition = [];
        $condition[] = ['p_code', '=', $p_code];
        $code = 200;
        $msg = '请求成功';
        $list = $areaModel
              ->where($condition)
              ->field('`name`,`code`,`center`,`cn_name`,`first_name`,`level`')
              ->select();
        $result_count = $areaModel->where($condition)->count();
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        $resultData['list'] = $list;
        $this->result($code, $msg, $result_code, $result_msg, $resultData, $result_count);
    }
}
